﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using System.Windows.Threading;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Controls.Data.Input;

using PermDoc.DB;
using PermDoc.Ctrl.Docs;


namespace PermDoc
{

    public partial class PageList : Page
    {

        #region Members
        private bool IsInit = false;
        Object ApplayFilterLock = new Object();
        protected static DispatcherTimer _timer_idle = new DispatcherTimer();
        private Uri _WelcomeUri = new Uri(@"/Welcome.xaml", UriKind.Relative);
        private Uri _DocUri = new Uri(@"/PageDoc.xaml", UriKind.Relative);
        #endregion
        #region Constructors
        public PageList()
        {
            InitializeComponent();
        }
        #endregion
        #region Page Events
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            App.IdleEmpty();
            App.PageListPtr = this;
            App.ListView = new PagedCollectionView(App.Topics);
            gv.ItemsSource = App.ListView;
            if (gv.Columns.Count > 0)
            {
                foreach (DataGridColumn c in gv.Columns)
                {
                    if (c.Header.ToString() == "ChildTopics")
                        c.Visibility = Visibility.Collapsed;
                }
            }
            oShopsCombo.ItemsSource = App.ListView_Shops;
            oCompanyCombo.ItemsSource = App.ListView_Company;
            ApplyGridStyles();

            _timer_idle.Tick += new EventHandler(myTimer_Idle);
            _timer_idle.Interval = new TimeSpan(0, 0, 1);
            _timer_idle.Start();

            IsInit = true;
        }
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            _timer_idle.Stop();
            App.PageListPtr = null;
            App.ListView = null;            
            gv.ItemsSource = null;
            IsInit = false;
        }
        private void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            App.IdleEmpty();
            if (App.isProcessGetData == false)
                gv.Visibility = System.Windows.Visibility.Visible;
            else
                gv.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void Page_KeyUp(object sender, KeyEventArgs e)
        {
            App.IdleEmpty();
        }
        void myTimer_Idle(object sender, EventArgs e)
        {
            if (App.Idle > App._idleMax)
            {
                if (App.MainPagePtr.navFrame.Source != _WelcomeUri)
                {
                    App.MainPagePtr.navFrame.Source = _WelcomeUri;
                }
            }
            else
            {
                if (App.isProcessGetData == false)
                    gv.Visibility = System.Windows.Visibility.Visible;
                else
                    gv.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        #endregion
        #region Controls Events
        private void gv_MouseMove(object sender, MouseEventArgs e)
        {
            App.IdleEmpty();
        }
        private void gv_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
        }
        private void gv_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            App.IdleEmpty();
        }
        private void gv_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            App.IdleEmpty();
        }
        private void oFindText_TextChanged(object sender, TextChangedEventArgs e)
        {
            FilterApplay();
        }
        private void Button_Click_Expand(object sender, RoutedEventArgs e)
        {
            if(App.ListView == null)
                return;
            if (App.ListView.CanGroup == false)
                return;
            PagedCollectionView pcv = gv.ItemsSource as PagedCollectionView;
            if (pcv.Groups == null)
                return;
            try
            {
                foreach (CollectionViewGroup group in pcv.Groups)
                {
                    gv.ExpandRowGroup(group, true);
                }
            }
            catch (Exception ex)
            {
                // Could not expand group.
                MessageBox.Show(ex.Message);
            }
        }
        private void Button_Click_Collapse(object sender, RoutedEventArgs e)
        {
            if (App.ListView == null)
                return;
            if (App.ListView.CanGroup == false)
                return;
            PagedCollectionView pcv = gv.ItemsSource as PagedCollectionView;
            if (pcv.Groups == null)
                return;
            try
            {
                foreach (CollectionViewGroup group in pcv.Groups)
                {
                    gv.ScrollIntoView(group, null);
                    gv.CollapseRowGroup(group, true);
                }
            }
            catch (Exception ex)
            {
                // Could not collapse group.
                MessageBox.Show(ex.Message);
            }
        }
        private void oShopsCheck_Checked(object sender, RoutedEventArgs e)
        {
            FilterApplay();
        }
        private void oShopsCheck_Unchecked(object sender, RoutedEventArgs e)
        {
            FilterApplay();
        }
        private void oCompanyCheck_Checked(object sender, RoutedEventArgs e)
        {
            FilterApplay();
        }
        private void oCompanyCheck_Unchecked(object sender, RoutedEventArgs e)
        {
            FilterApplay();
        }
        private void oShopsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void oCompanyCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void oApprovedCheck_Checked(object sender, RoutedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void oApprovedCheck_Unchecked(object sender, RoutedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void oApprovedCheck2_Checked(object sender, RoutedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void oApprovedCheck2_Unchecked(object sender, RoutedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void oApprovedCheck3_Checked(object sender, RoutedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void oApprovedCheck3_Unchecked(object sender, RoutedEventArgs e)
        {
            if (IsInit == false)
                return;
            FilterApplay();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Topic sel = (Topic)gv.SelectedItem;
            if (sel != null)
            {
                App.SelectedDocumentTopic = new Topic(sel);
                App.MainPagePtr.navFrame.Source = _DocUri;
            }
        }
        #endregion
        #region Common Methods
        public void ApplyGridStyles()
        {
            if(App.IsNight() == false)
                return;            
            if (App.ListView == null)
                return;
            if (App.ListView.CanGroup == true)
            {
                App.ListView.GroupDescriptions.Clear();
                App.ListView.GroupDescriptions.Add(new PropertyGroupDescription("Дата_Док"));
                App.ListView.GroupDescriptions.Add(new PropertyGroupDescription("Контрагент"));
                //App.ListView.GroupDescriptions.Add(new PropertyGroupDescription("Магазин"));
            }
            if (App.ListView.CanSort == true)
            {
                App.ListView.SortDescriptions.Clear();
                App.ListView.SortDescriptions.Add(new SortDescription("Дата_Док", ListSortDirection.Descending));
                //App.ListView.SortDescriptions.Add(new SortDescription("Магазин", ListSortDirection.Descending));
            }
        }
        #endregion
        #region Data
        public void FilterApplay()
        {
            if (gv.ItemsSource == null)
                return;
            lock (ApplayFilterLock)
            {
                #region Members
                PagedCollectionView pcv = this.gv.ItemsSource as PagedCollectionView;
                string str = oFindText.Text.ToLower().Trim();
                string str2 = "";
                if (oShopsCombo.SelectedValue != null)
                    str2 = oShopsCombo.SelectedValue.ToString().ToLower().Trim();
                string str3 = "";
                if (oCompanyCombo.SelectedValue != null)
                    str3 = oCompanyCombo.SelectedValue.ToString().ToLower().Trim();
                bool find = false;
                string no = "";
                string shop = "";
                string ko = "";
                if (
                    String.IsNullOrEmpty(str)
                    && oShopsCheck.IsChecked == false
                    && oCompanyCheck.IsChecked == false
                    && oApprovedCheck.IsChecked == true
                    && oApprovedCheck2.IsChecked == true
                    && oApprovedCheck3.IsChecked == true)
                {
                    pcv.Filter = null;
                    foreach (Topic o in App.Topics)
                        o.IsVisible = true;
                    return;
                }
                pcv.Filter = null;
                #endregion
                #region Process
                foreach (Topic o in App.Topics)
                {
                    find = false;
                    no = "";
                    if (o.No != null)
                        no = o.No.ToLower().Trim();
                    shop = "";
                    if (o.Магазин.Name != null)
                        shop = o.Магазин.Name.ToLower().Trim();
                    ko = "";
                    if (o.Контрагент.Name != null)
                        ko = o.Контрагент.Name.ToLower().Trim();

                    if (no.IndexOf(str) >= 0)
                        find = true;
                    else if (shop.IndexOf(str) >= 0)
                        find = true;
                    else if (ko.IndexOf(str) >= 0)
                        find = true;
                    else
                        find = false;

                    if (find == true && oApprovedCheck.IsChecked == false && o.Статус == DocState.Утвержден)
                        find = false;

                    if (find == true && oApprovedCheck2.IsChecked == false && o.Статус == DocState.Черновик)
                        find = false;

                    if (find == true && oApprovedCheck3.IsChecked == false && o.Статус == DocState.Ожидает_утверждения)
                        find = false;

                    if (find == true && oShopsCheck.IsChecked == true)
                    {
                        if (oShopsCombo.SelectedValue != null)
                        {
                            if (shop != str2)
                                find = false;
                        }
                    }

                    if (find == true && oCompanyCheck.IsChecked == true)
                    {
                        if (oCompanyCombo.SelectedValue != null)
                        {
                            if (ko != str3)
                                find = false;
                        }
                    }

                    if (find == true)
                        o.IsVisible = true;
                    else
                        o.IsVisible = false;
                }
                #endregion
                pcv.Filter = new Predicate<object>(FilterMethod);
            }
        }
        public bool FilterMethod(object t)
        {
            if (t == null)
                return false;
            Topic o = t as Topic;
            return (o.IsVisible == true);
        }
        #endregion

    }

}
